package com.booktrading.controller;

import com.booktrading.model.User;
import com.booktrading.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    
    /**
     * 用户注册页面
     */
    @GetMapping("/register")
    public String registerPage() {
        return "user/register";
    }
    
    /**
     * 用户注册处理
     */
    @PostMapping("/register")
    public String register(@ModelAttribute User user, Model model) {
        // 注册用户
        User registeredUser = userService.register(user);
        
        if (registeredUser != null) {
            model.addAttribute("message", "注册成功！请登录");
            model.addAttribute("messageType", "alert-success");
            return "redirect:/user/login";
        } else {
            model.addAttribute("message", "注册失败，用户名可能已存在");
            model.addAttribute("messageType", "alert-danger");
            return "user/register";
        }
    }
    
    /**
     * 用户登录页面
     */
    @GetMapping("/login")
    public String loginPage() {
        return "user/login";
    }

    @GetMapping("/profile")
    public String profile(Model model) {
        // 获取当前登录用户
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        User user = userService.getUserByUsername(auth.getName());
        model.addAttribute("user", user);
        return "user/profile";
    }
} 